import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default class BasePage {
  constructor() {
    let config = {
      // components: {
      // },
      // props: {},
      datas: {
        downLoading: false,
      },
      methods: {
        /**
         * 批量下载
         */
        async downZip(selectedRows, fileListName = 'fileInfoList',fileName = this.$route.meta.title) {
          // 若选中项为Map,则格式化为Array
          if (selectedRows instanceof Map) {
            selectedRows = Array.from(selectedRows, item => item[1])?.[0]
          }
          let downZip = require('@/api').downZip // 下载api
          let commonIds = selectedRows.map((item) => item[fileListName].map((i) => i.commonId)).reduce((pre, cur) => pre.concat(cur)) // 文件id集合
          // 下载 
          this.downLoading = true
          await downZip({
            fileIds: commonIds,
            urlStr: location.origin
          }, fileName)
          this.downLoading = false
        },
        /**
         * 删除草稿:api 请求api
         */
        handleRemove(id, callback, msg='请确定是否要删除该条数据？') {
          this.$confirm({
            title: '温馨提示',
            content: msg,
            onOk: () => {
              return this.removeApi?.remove({
                id
              }).then(() => {
                this.$message.success('删除成功！')
                if (callback) {
                  // 初始化选中项
                  this.$refs.table?.selectedRowKeys?.length > 0 && (this.$refs.table.selectedRowKeys.length = 0)
                  this.$refs.table?.selectedRowsMap && (this.$refs.table.selectedRowsMap = new Map())
                  callback()
                } else {
                  this.$refs.table.loadData()
                }
              })
            },
          })
        },
        /**
        * 删除草稿:api 请求api;params 请求参数为对象
        */
        handleRemoveParams(params, callback) {
          this.$confirm({
            title: '温馨提示',
            content: '请确定是否要删除该条数据？',
            onOk: () => {
              return this.removeApi?.remove(params).then(() => {
                this.$message.success('删除成功！')
                if (callback) {
                  // 初始化选中项
                  this.$refs.table?.selectedRowKeys?.length > 0 && (this.$refs.table.selectedRowKeys.length = 0)
                  this.$refs.table?.selectedRowsMap && (this.$refs.table.selectedRowsMap = new Map())
                  callback()
                } else {
                  this.$refs.table.loadData()
                }
              })
            },
          })
        },
        /**
         * 撤销:api 请求api;params 请求参数
         */
        handleUndo(params, callback) {
          this.$confirm({
            title: '温馨提示',
            content: '请确定是否要撤销该条数据？',
            onOk: () => {
              return this.removeApi?.undo(params).then(() => {
                this.$message.success('撤销成功！')
                if (callback) {
                  // 初始化选中项
                  this.$refs.table?.selectedRowKeys?.length > 0 && (this.$refs.table.selectedRowKeys.length = 0)
                  this.$refs.table?.selectedRowsMap && (this.$refs.table.selectedRowsMap = new Map())
                  callback()
                } else {
                  this.$refs.table.loadData()
                }
              })
            },
          })
        },
        /**
         * 作废api 请求api;params 请求参数
         */
        handleInvalid(params, callback) {
          console.log(this.removeApi.invalid)
          this.$confirm({
            title: '温馨提示',
            content: '请确定是否要作废该条数据？',
            onOk: () => {
              return this.removeApi?.invalid(params).then((res) => {
                if (res?.data?.code == 200 || res[1]?.data?.code == 200 || res.code == 0) {
                  this.$message.success('作废成功！')
                  if (callback) {
                    // 初始化选中项
                    this.$refs.table?.selectedRowKeys?.length > 0 && (this.$refs.table.selectedRowKeys.length = 0)
                    this.$refs.table?.selectedRowsMap && (this.$refs.table.selectedRowsMap = new Map())
                    callback()
                  } else {
                    this.$refs.table.loadData()
                  }
                }
              })
            },
          })
        },

        /**
         * 状态跟新:api 请求api;params 请求参数
         */
        handleUpdate(id, callback, msg = '请确定是否已办理？') {
          this.$confirm({
            title: '温馨提示',
            content: msg,
            onOk: () => {
              return this.updateApi?.update({
                id
              }).then(() => {
                this.$message.success('更新成功！')
                if (callback) {
                  callback()
                } else {
                  this.$refs.table.loadData()
                }
              })
            },
          })
        },
        /**
         * 删除草稿:api 请求api;params 请求参数 批量删除
         */
        handleRemoves(ids) {

          this.$confirm({
            title: '温馨提示',
            content: '确定删除？',
            onOk: () => {
              return this.removeApi?.remove({
                ids: ids
              }).then(() => {
                this.$message.success('删除成功！')
                this.$refs.table.loadData()
              })
            },
          })
        },
        /**
         * @description: 导出点位信息（参考jquery.wordexport.js源码)
         * @param {*} el：导出的列表
         * @param {*} fileName：导出文件名称
         * @param {*} formType：导出文件类型：默认为word格式：.doc
         * @return {*}
         */
        exportPointInfo(datas, fileName, formType = '.doc') {
          let list = [] // word列表集合
          for (let index in datas) {
            let item = datas[index]
            /**
             * jquery.wordexport.js源码——START
             */
            let statics = {
              mhtml: {
                top:
                  'Mime-Version: 1.0\nContent-Base: ' +
                  location.href +
                  '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
                  location.href +
                  '\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
                head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
                body: '<body>_body_</body>'
              }
            }
            let options = {
              maxWidth: 624
            }
            // Embed all images using Data URLs
            var images = Array()
            let inerHTML = item.content
            let el = document.createElement('div')
            el.innerHTML = inerHTML
            let img = el.getElementsByTagName('img')
            let reg =
              /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i
            for (var i = 0; i < img.length; i++) {
              if (img[i].width && img[i].height) {
                let uri
                // 如果是base64格式输出该base64
                if (reg.test(img[i].src)) {
                  uri = img[i].src
                } else {
                  // Calculate dimensions of output image
                  var w = Math.min(img[i].width, options.maxWidth)
                  var h = img[i].height * (w / img[i].width)
                  // Create canvas for converting image to data URL
                  var canvas = document.createElement('CANVAS')
                  canvas.width = w
                  canvas.height = h
                  // Draw image to canvas
                  var context = canvas.getContext('2d')
                  context.drawImage(img[i], 0, 0, w, h)
                  // Get data URL encoding of image
                  uri = canvas.toDataURL('image/png/jpg')
                  // $(img[i]).attr('src', img[i].src)
                  img[i].width = w
                  img[i].height = h
                }
                // Save encoded image to array
                images.push({
                  type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
                  encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
                  location: img[i].src,
                  data: uri.substring(uri.indexOf(',') + 1)
                })
              }
            }
            let mhtmlBottom = '\n'
            for (var i = 0; i < images.length; i++) {
              mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n'
              mhtmlBottom += 'Content-Location: ' + images[i].location + '\n'
              mhtmlBottom += 'Content-Type: ' + images[i].type + '\n'
              mhtmlBottom += 'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n'
              mhtmlBottom += images[i].data + '\n\n'
            }
            mhtmlBottom += '--NEXT.ITEM-BOUNDARY--'

            let styles = ''
            // Aggregate parts of the file together
            let fileContent =
              statics.mhtml.top.replace(
                '_html_',
                statics.mhtml.head.replace('_styles_', styles) + statics.mhtml.body.replace('_body_', inerHTML)
              ) + mhtmlBottom

            // Create a Blob with the file contents
            let blob = new Blob([fileContent], {
              type: `application/${formType === '.pdf' ? 'pdf' : 'msword'};charset=utf-8`
            })
            console.log(`application/${formType === '.pdf' ? 'pdf' : 'msword'};charset=utf-8`)
            // 清空dom变量
            el = null
            img = null
            list.push({ name: item.name, url: blob })
            if (index == datas.length - 1) {
              const JSZip = require('jszip')
              const zip = new JSZip()
              for (let item of list) {
                zip.file(item.name + formType, item.url, { binary: true }) // 逐个添加文件，需要加后缀".doc"
              }
              zip.generateAsync({ type: 'blob' }).then((content) => {
                const FileSaver = require('file-saver')
                console.log(FileSaver)
                // 生成二进制流
                FileSaver.saveAs(content, fileName) // 利用file-saver保存文件  自定义文件名
                this.$message.success('导出成功！')
              })
            }
          }
        },
        getPdf(dom) {
          return new Promise((resolve) => {
            html2Canvas(dom, {
              allowTaint: true,
            }).then((canvas) => {
              // let contentWidth = canvas.width
              // let contentHeight = canvas.height
              // let pageHeight = contentWidth / 592.28 * 841.89
              // let leftHeight = contentHeight
              // let position = 0
              // let imgWidth = 595.28
              // let imgHeight = 592.28 / contentWidth * contentHeight
              let pageData = canvas.toDataURL('image/jpeg', 1.0)
              let PDF = new JsPDF('', 'pt', 'a4')
              PDF.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28/canvas.width * canvas.height );
              // if (leftHeight < pageHeight) {
              //   PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
              // } else {
              //   while (leftHeight > 0) {
              //     PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
              //     leftHeight -= pageHeight
              //     position -= 841.89
              //     if (leftHeight > 0) {
              //       PDF.addPage()
              //     }
              //   }
              // }
              // Create a Blob with the file contents
              var arr = PDF.output("datauristring").split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
              }
              // console.log(mime)
              resolve(new Blob([u8arr], { type: mime }))
            }
            )
          }
          )
        },
        getPdfMore(dom) {
          return new Promise((resolve) => {
            html2Canvas(dom, {
              allowTaint: true,
              height: dom.scrollHeight,//canvas高
              width: dom.scrollWidth, //canvas宽
              scale: 2, //按比例增加分辨率 (2=双倍).
              dpi: window.devicePixelRatio * 2,//设备像素比
            }).then((canvas) => {
              let contentWidth = canvas.width
              let contentHeight = canvas.height
              let pageHeight = contentWidth / 592.28 * 841.89
              let leftHeight = contentHeight
              let position = 0
              let imgWidth = 595.28
              let imgHeight = 592.28 / contentWidth * contentHeight
              let pageData = canvas.toDataURL('image/jpeg', 1.0)
              let PDF = new JsPDF('', 'pt', 'a4')
              if (leftHeight < pageHeight) {
                PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
              } else {
                while (leftHeight > 0) {
                  PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                  leftHeight -= pageHeight
                  position -= 841.89
                  if (leftHeight > 0) {
                    PDF.addPage()
                  }
                }
              }
              // Create a Blob with the file contents
              var arr = PDF.output("datauristring").split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
              }
              // console.log(mime)
              resolve(new Blob([u8arr], { type: mime }))
            }
            )
          }
          )
        },
        /**
         * @description: 导出PDF
         * @param {*} datas：导出的列表
         * @param {*} fileName：导出的文件名
         * @param {*} beforeCallback：导出之前回调
         * @param {*} afterCallback：导出之后回调
        */
        async exportPdf(datas, fileName, beforeCallback, afterCallback) {
          let list = [] // word列表集合
          for (let index in datas) {
            let item = datas[index]
            document.getElementById('print-box').innerHTML = item.content?item.content:item.contentHtml;
            let blob = null;
            if(item.content){
              blob = await this.getPdf(document.getElementById('print-box'))
            }else{
              blob = await this.getPdfMore(document.getElementById('print-box'))
            }

            list.push({ name: item.name, url: blob })
            beforeCallback?.(list)
            console.log(list)
            if (index == datas.length - 1) {
              const JSZip = require('jszip')
              const zip = new JSZip()
              for (let item of list) {
                zip.file(item.name + '.pdf', item.url, { binary: true }) // 逐个添加文件，需要加后缀".doc"
              }
              zip.generateAsync({ type: 'blob' }).then((content) => {
                const FileSaver = require('file-saver')
                // 生成二进制流
                FileSaver.saveAs(content, fileName) // 利用file-saver保存文件  自定义文件名
                afterCallback?.()
                this.$message.success('导出成功！')
              })
            }
          }
        }
      },
    }
    config.data = function () {
      return config.datas
    }
    return config
  }
}